package com.carryGo.web.hzl;

import com.carryGo.entity.Commodity;
import com.carryGo.entity.PageManager;
import com.carryGo.entity.User;
import com.carryGo.service.lt.CommodityService;
import com.carryGo.utils.WebUtils;
import com.carryGo.utils.dp.EncryptCodeUtils;


import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * ClassName:CommodityServlet
 * package:
 * Desription:
 *
 * @Date:2020/8/27 14:16
 * @Author: tank_李涛
 *//*
 *FileName:  CommodityServlet
 * Author:   28633
 * Date  :   2020/8/27 14:16
 * */
@WebServlet("/commoditylt")
@MultipartConfig
public class CommodityServlet extends HttpServlet {

    private CommodityService commService = new CommodityService();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method=request.getParameter("method");
        switch (method){
            case "toShowCommodity":
                WebUtils.toRequestPage(request,response,"showCommodity");
                break;
            case "toAddCommodity":
                WebUtils.toRequestPage(request,response,"addCommodity");
                break;
            case "queryCommoditys":
                queryCommoditys(request,response);
                break;
            case "addCommoditys":
                addCommoditys(request,response);
                break;
            case "delCommoditys":
                delCommoditys(request,response);
                break;
            case "updateCommoditys":
                updateCommoditys(request,response);
                break;
            case "queryCommodity":
                queryCommodity(request,response);
                break;
        }
    }

    /**
     * 修改数据
     * @param request
     * @param response
     */
    private void updateCommoditys(HttpServletRequest request, HttpServletResponse response) {
        Commodity commodity = WebUtils.getBean(Commodity.class, request);
        String path = null;
        try {
            path = WebUtils.uploadFile(request, "newPic");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
        //如果path是空，新的图片没上传，不做修改
        commodity.setPic(path==null?commodity.getPic():path);

       /* String password = user.getPassword();
        if (password != null && !password.equals("")) {
            //密码不为空的时候，证明用户修改过密码，重新设置密码
            //设置盐值
            user.setSalt(WebUtils.getRandomString());
            //重新设置密码
            user.setPassword(EncryptCodeUtils.getEncryptStr(user.getPassword(),
                    user.getSalt()));
        } else {
            //通过用户名重新查询一遍用户，得到这个密码和盐值
            User queryUser = userService.queryUserByUsername(user.getUsername());
            //设置密码
            user.setPassword(queryUser.getPassword());
            //重新设置盐值
            user.setSalt(queryUser.getSalt());
        }*/

        //修改
        boolean result = commService.updateCommodity(commodity);
        /*User loginUser = (User) request.getSession().getAttribute("username");*/

       /* if (result && loginUser.getId() == user.getId()) {
            request.getSession().setAttribute("user", user);
        }
*/
        PageManager pm = (PageManager) request.getSession().getAttribute("pm");

        request.getSession().setAttribute("msg", result?"修改成功":"修改失败");
        request.getSession().setAttribute("result", result);


        try {
            response.sendRedirect("commoditylt?method=queryCommoditys&pn="+(pm==null?"":pm.getPn()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询单个用户数据
     */
    private void queryCommodity(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Commodity commodity = commService.queryCommodity(id);
        request.setAttribute("commodity", commodity);
        request.setAttribute("outerLi", "commodity");
        request.setAttribute("innerLi", "showCommodity");
        WebUtils.toRequestPage(request, response, "updateCommodity");
    }
    /**
     * 删除数据
     * @param request
     * @param response
     */
    private void delCommoditys(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));
        PageManager pm = (PageManager) request.getSession().getAttribute("pm");
        if (pm != null) {
            pm.setTotalCount(pm.getTotalCount()-1);
            pm.setPages();
            //删除之后，正好最后一页没了，直接使用最后一页当作当前页
            pm.setPn(pm.getPn()>=pm.getPages()?pm.getPages():pm.getPn());
        }
        boolean result = commService.deleCommodity(id);
        request.getSession().setAttribute("msg", result?"删除成功":"删除失败");
        request.getSession().setAttribute("result", result);
        try {
            response.sendRedirect("commoditylt?method=queryCommoditys&pn="+((pm==null)?"":pm.getPn()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 增加数据
     * @param request
     * @param response
     * @throws IOException
     */
    private void addCommoditys(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Commodity commodity = WebUtils.getBean(Commodity.class,request);
//        System.out.println("commdity=" + commodity);
      /*  user.setSalt(WebUtils.getRandomString());//设置盐值
        user.setPassword(EncryptCodeUtils.getEncryptStr(user.getPassword(),user.getSalt()));//设置加密后的密码*/
        PageManager pm = (PageManager) request.getSession().getAttribute("pm");
        if (pm != null) {
            pm.setTotalCount(pm.getTotalCount()+1);
            pm.setPages();
        }
        boolean result = commService.addCommodity(commodity);
        request.getSession().setAttribute("msg", result?"增加成功":"增加失败");
        request.getSession().setAttribute("result", result);
        response.sendRedirect("commoditylt?method=queryCommoditys&pn="+(pm==null?"":pm.getPages()));
    }


    /**
     * 查询所有数据
     */
    private void queryCommoditys(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PageManager pm = WebUtils.getBean(PageManager.class, request);
        List<Commodity> commoditys = commService.queryCommodity(pm);
        int totalCount = commService.queryCommodityTotalCount();
        pm.setTotalCount(totalCount);//总数据数
        pm.setPages();//设置总页数

        request.setAttribute("commoditys", commoditys);
        request.getSession().setAttribute("pm", pm);
        request.setAttribute("outerLi", "commodity");
        request.setAttribute("innerLi", "showCommodity");
        WebUtils.toRequestPage(request, response, "showCommodity");
    }
}
